package com.metroinfo.test.client;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;

import com.metroinfo.parser.GeneralSettings;

public class SimpleClient {

	public static void main(String[] args) {
		// declaration section:
		// smtpClient: our client socket
		// os: output stream
		// is: input stream
		Socket smtpSocket = null;
		DataOutputStream os = null;
		DataInputStream is = null;
		// BufferedReader bis = null;
		// Initialization section:
		// Try to open a socket on port 25
		// Try to open input and output streams
		try {
			smtpSocket = new Socket("localhost", 8000);
			os = new DataOutputStream(smtpSocket.getOutputStream());
			is = new DataInputStream(smtpSocket.getInputStream());
			// bis = new BufferedReade(smtpSocket.getInputStream());
		} catch (UnknownHostException e) {
			System.err.println("Don't know about host: hostname");
		} catch (IOException e) {
			System.err
					.println("Couldn't get I/O for the connection to: hostname");
		}
		// If everything has been initialized then we want to write some data
		// to the socket we have opened a connection to on port 25
		if (smtpSocket != null && os != null && is != null) {
			try {
				// The capital string before each colon has a special meaning to
				// SMTP
				// you may want to read the SMTP specification, RFC1822/3
				ByteBuffer bb = ByteBuffer.allocate(10);
				bb.put((byte)GeneralSettings.CT_SEND_DATA);
				bb.putShort((short)1323);
				bb.putShort((short)212);
				bb.put((byte)1);
				
				bb.putShort((short)323);
				bb.put((byte)23);
				
				bb.put((byte)0);
				os.write( bb.array());
				os.flush();
				// keep on reading from/to the socket till we receive the "Ok"
				// from SMTP,
				// once we received that then we want to break.
				String responseLine;
				responseLine = is.readLine();
				// while ((responseLine = is.readLine()) != null) {
				// while ((responseLine = bis. readLine()) != null) {
				System.out.println("Server: " + responseLine);
				/*if (responseLine.indexOf("Ok") != -1) {
					break;
				}*/

				// clean up:
				// close the output stream
				// close the input stream
				// close the socket
				os.close();
				is.close();
				smtpSocket.close();
			} catch (UnknownHostException e) {
				System.err.println("Trying to connect to unknown host: " + e);
			} catch (IOException e) {
				System.err.println("IOException:  " + e);
			}
		}
	}
}